'''
tremmumble.py contains one class TremOper. 
This class is an 'operator' of mumble. It manages the users connected 
to the mumble server via using dbus. Information about players in the
game is collected from info messages requested to the tremulous server.
This script place the players in the expected channels "Aliens" or "Humans"

Example:

from tremmumble import TremOper

oper=TremOper("78.47.88.170:27940");
oper.run()

'''

from tremapi import TremListener
from tremulous import TremulousProtocol
from mumble import Mumble
from twisted.internet import gtk2reactor
gtk2reactor.install()
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
from string import split,join,atoi
from array import array
from struct import unpack
from time import time

class TremMumble(TremListener):
	def __init__(self):
		self.bus = dbus.SystemBus()
		self.obj = self.bus.get_object('net.sourceforge.mumble.murmur', '/1')
		self.setPlayerState=self.obj.setPlayerState
	def getPlayers(self):
		p=self.obj.getPlayers()
		return p
	

class TremOper:
	info_path='/home/tremded/.tremulous/base/info/info-mumble.txt'
	tr={'Alien':1, 'Humano':2, 'Espectador':3}
	def __init__(self, addr):
		self.trem=TremulousProtocol()
		self.addr=addr
		self.mumble=Mumble()
	
	def save_info_file(self, path, players_trem, players_mumble):
		playernames=[]
		print ("Guardando info en %s" % path)	
		f=file(path, 'wt')
		for p in players_mumble:
			playernames.append(p[8])
		f.write("^2Mumble users online:\n^3")
		f.write(', '.join(playernames))
		f.write("\n")
		f.close()

	def trem_cb(self, addr, info, players):
		p=self.mumble.getPlayers()
		for i in range(len(p)):
			channel=p[i][6]
			name=p[i][8]
			
			for j in range(len(players)):
				if(name==players[j][2]):
					channel2=self.tr[players[j][3]]
					if (channel!=channel2):
						print "Canal equivocado, movemos"
						self.mumble.setPlayerState((p[i][0], p[i][1], p[i][2], p[i][3], p[i][4], p[i][5], channel2,))
						self.save_info_file(self.info_path, players, p)
					
		
	def run(self):
		reactor.listenUDP(0, self.trem)
		self.trem.servers.doSent(self.addr, False)
		self.trem.addCallback(self.addr,self.trem_cb)
		reactor.run()
		
